package com.xhy.documents_collection.aop;

import com.xhy.documents_collection.exception.BaseException;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.restrict.RestrictHandler;
import com.xhy.documents_collection.annotations.Restriction;
import com.xhy.documents_collection.utils.JwtUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Author: Xhy
 * CreateTime: 2023-03-08 09:40
 */
@Aspect
@Component
public class RestrictAop {

    @Autowired
    HttpServletRequest request;

    @Autowired
    RestrictHandler restrictHandler;

    @Before("@annotation(restriction)")
    public void restriction(JoinPoint joinPoint, Restriction restriction)  {
        Integer userId = UserHolder.get();
        String key = request.getRequestURI() + userId;

        int limit = restriction.limit();
        int time = restriction.time();
        restrictHandler.incr(key, time);
        boolean result = restrictHandler.check(key, limit);
        if (result) {
            throw new BaseException(500, "访问次数过多,你已被限制");
        }
    }

}
